/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.auxiliares;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.grupoavatar.guiaubicua.mix.MixContext;
import org.grupoavatar.guiaubicua.punto.TabGeneral;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

public class Red {

	private String red;
	private String url;
	
	public static ProgressDialog pd;
	
	public Red(String red, String url) {
		this.red = red;
		this.url = url;
	}
	
	public boolean tieneFB() { //facebook
		boolean flag = false;
		if (red.equalsIgnoreCase("FB")) flag= true;
		return flag;
	}
	
	public boolean tieneTW() { //twitter
		boolean flag = false;
		if (red.equalsIgnoreCase("TW")) flag= true;
		return flag;
	}
	
	public boolean tieneYT() { //youtube
		boolean flag = false;
		if (red.equalsIgnoreCase("YT")) flag= true;
		return flag;
	}
	
	public boolean tieneFS() { //Foursquare
		boolean flag = false;
		if (red.equalsIgnoreCase("FS")) flag= true;
		return flag;
	}
	
	public boolean tieneGP() { //Google plus
		boolean flag = false;
		if (red.equalsIgnoreCase("GP")) flag= true;
		return flag;
	}
	
	public String getUrl() {
		return url;
	}
	
	public static void getOpenFacebookIntent(final TabGeneral context,final String ruta) {
		System.out.println("ruta : "+ruta);
		pd = new ProgressDialog(context);
		
		Thread cargarFB = new Thread()
		{
			@Override
			public void run() {
				try {		    
				    String id ="";
				    String id_fb = ruta.substring(ruta.lastIndexOf("/")+1);
				    System.out.println("id_fb : "+id_fb);
				    InputStream input = getHttpGETInputStream("https://graph.facebook.com/"+id_fb);
				    String temp = getHttpInputString(input);			    
				    JSONObject root = new JSONObject(temp);			    
				    id = root.getString("id");
				    System.out.println("id : "+id);
				    context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
				    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/"+id));
				    
				    try {
						if (pd != null && pd.isShowing()) {
							pd.dismiss();
							pd = null;
							context.startActivity(intent);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} catch (Exception e) {			   
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.addCategory(Intent.CATEGORY_BROWSABLE);
					intent.setData(Uri.parse(ruta));
					
					try {
						if (pd != null && pd.isShowing()) {
							pd.dismiss();
							context.startActivity(intent);
						}
					} catch (Exception e2) {
						e2.printStackTrace();
					}
			    //return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/alvaro.aguero"));
				}
			}
		};
		   
		pd.setMessage("Cargando...");
		pd.setButton("Cancelar", new DialogInterface.OnClickListener() 
	    {
	        public void onClick(DialogInterface dialog, int which) 
	        {		
	        	return;
	        }
	    });
		pd.show();
		
		cargarFB.start();
	}
	
	public static String getHttpInputString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8 * 1024);
		StringBuilder sb = new StringBuilder();

		try {
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static InputStream getHttpGETInputStream(String urlStr)
			throws Exception {
				InputStream is = null;
				URLConnection conn = null;

				if (urlStr.startsWith("file://"))			
					return new FileInputStream(urlStr.replace("file://", ""));

				if (urlStr.startsWith("content://"))
					return getContentInputStream(urlStr, null);

				if (urlStr.startsWith("https://")) {
					HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
		    			public boolean verify(String hostname, SSLSession session) {
		    				return true;
		    			}});
				SSLContext context = SSLContext.getInstance("TLS");
				context.init(null, new X509TrustManager[]{new X509TrustManager(){
					public void checkClientTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {}
					public void checkServerTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {}
					public X509Certificate[] getAcceptedIssuers() {
						return new X509Certificate[0];
					}}}, new SecureRandom());
				HttpsURLConnection.setDefaultSSLSocketFactory(
						context.getSocketFactory());
				}
				
				try {
					URL url = new URL(urlStr);
					conn =  url.openConnection();
					conn.setReadTimeout(10000);
					conn.setConnectTimeout(10000);

					is = conn.getInputStream();
					
					return is;
				} catch (Exception ex) {
					try {
						is.close();
					} catch (Exception ignore) {			
					}
					try {
						if(conn instanceof HttpURLConnection)
							((HttpURLConnection)conn).disconnect();
					} catch (Exception ignore) {			
					}
					
					throw ex;				

				}
			}
	
	public static InputStream getContentInputStream(String urlStr, String params)
			throws Exception {
				ContentResolver cr = MixContext.mixcontext.var.getContentResolver();
				Cursor cur = cr.query(Uri.parse(urlStr), null, params, null, null);

				cur.moveToFirst();
				int mode = cur.getInt(cur.getColumnIndex("MODE"));

				if (mode == 1) {
					String result = cur.getString(cur.getColumnIndex("RESULT"));
					cur.deactivate();

					return new ByteArrayInputStream(result
							.getBytes());
				} else {
					cur.deactivate();

					throw new Exception("Invalid content:// mode " + mode);
				}
			}

	public static Intent getOpenFoursquareIntent(MixContext context, String ruta) {
		// TODO Auto-generated method stub
		String id_fs = ruta.substring(ruta.lastIndexOf("/")+1);
		Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://m.foursquare.com/venue/"+id_fs));
        return intent;
	}
}
